package com.demo.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.auth.config.OauthProperties;
import com.demo.auth.dao.domain.OauthClientDetails;
import com.demo.auth.dao.service.OauthClientDetailsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Oauth客户端数据获取服务
 */
@Slf4j
@Service("jdbcClientDetailsService")
public class JdbcClientDetailsService implements ClientDetailsService {

    @Resource
    private OauthClientDetailsService oauthClientDetailsService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private OauthProperties oauthProperties;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        String value = stringRedisTemplate.opsForValue().get(clientId);
        if (StringUtils.isNotBlank(value)) {
            try {
                log.info("从缓存获取ClientDetails信息，clientId：{}", clientId);
                return objectMapper.readValue(value, BaseClientDetails.class);
            } catch (JsonProcessingException e) {
                log.error("", e);
                throw new RuntimeException(e);
            }
        }

        OauthClientDetails clientDetails = oauthClientDetailsService.lambdaQuery().eq(OauthClientDetails::getClientId, clientId).one();

        BaseClientDetails baseClientDetails = new BaseClientDetails(clientDetails.getClientId(), clientDetails.getResourceIds(),
                clientDetails.getScope(), clientDetails.getAuthorizedGrantTypes(), clientDetails.getAuthorities(),
                clientDetails.getWebServerRedirectUri());
        baseClientDetails.setClientSecret(oauthProperties.getPasswordEncode() + clientDetails.getClientSecret());
        baseClientDetails.setAccessTokenValiditySeconds(clientDetails.getAccessTokenValidity());
        baseClientDetails.setRefreshTokenValiditySeconds(clientDetails.getRefreshTokenValidity());

        if (StringUtils.isNotBlank(clientDetails.getAdditionalInformation())) {
            JSONObject jsonObject = JSON.parseObject(clientDetails.getAdditionalInformation());
            baseClientDetails.setAdditionalInformation(jsonObject);
        }
        if (StringUtils.isNotBlank(clientDetails.getScope())) {
            baseClientDetails.setAutoApproveScopes(org.springframework.util.StringUtils.commaDelimitedListToSet(clientDetails.getScope()));
        }

        try {
            String json = objectMapper.writeValueAsString(baseClientDetails);
            stringRedisTemplate.opsForValue().setIfAbsent(clientId, json, 1, TimeUnit.MINUTES);
        } catch (JsonProcessingException e) {
            log.warn("BaseClientDetails转换json异常，不会存放redis，不影响业务", e);
        }
        return baseClientDetails;
    }
}
